/*              Copyright(c) 2008 Dave Sexton              *
 * http://www.codeplex.com/DocProject                      *
 * http://www.codeplex.com/DocProject/Project/License.aspx *
 ***********************************************************/
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.ComponentModel;

namespace DaveSexton.Sandcastle
{
	[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable"), 
	DisplayName("XML mappings"), Description("Parses URL mappings from the inner XML of a mappings group.")]
	public sealed class XmlUrlMappingProvider : UrlMappingProvider
	{
		#region Public Properties
		[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")]
		public static readonly XmlUrlMappingProvider Instance = new XmlUrlMappingProvider();
		#endregion

		#region Private / Protected
		private XmlUrlMappingProviderEditor editor;
		#endregion

		#region Constructors
		/// <summary>
		/// Constructs a new instance of the <see cref="XmlUrlMappingProvider" /> class for the <see cref="Instance"/> singleton.
		/// </summary>
		private XmlUrlMappingProvider()
		{
		}
		#endregion

		#region Methods
		public override IEnumerable<UrlMapping> GetMappings(UrlMappingGroup group, string configuration)
		{
			if (string.IsNullOrEmpty(configuration))
				yield break;

			XmlReaderSettings settings = new XmlReaderSettings();
			settings.IgnoreComments = true;
			settings.IgnoreProcessingInstructions = true;
			settings.IgnoreWhitespace = true;

			using (System.IO.StringReader input = new System.IO.StringReader(configuration))
			{
				using (XmlReader reader = XmlReader.Create(input, settings))
				{
					while (reader.ReadToFollowing("url"))
					{
						if (reader.Depth == 1)
							yield return new UrlMapping(reader.GetAttribute("id"), reader.GetAttribute("href"));
					}
				}
			}
		}

		public override System.Windows.Forms.Control GetEditor(UrlMappingGroup group, string configuration)
		{
			if (editor == null || !editor.Created)
				editor = new XmlUrlMappingProviderEditor();

			editor.Configuration = configuration;
			return editor;
		}

		public override string GetEditorConfiguration(UrlMappingGroup group, System.Windows.Forms.Control control)
		{
			return editor.Configuration;
		}
		#endregion
	}
}
